<template>
  <div id="pay-insurance-detail-confirm">
    <header class="banner">
      <div>
        <h2 class="ha logo" v-if="$route.query.company_id === '1'"></h2>
        <h2 class="astp logo" v-else-if="$route.query.company_id === '2'"></h2>
        <h2 class="dh logo" v-else-if="$route.query.company_id === '3'"></h2>
        <h2 class="rb logo" v-else-if="$route.query.company_id === '4'"></h2>
        <h2 class="bbw logo" v-else-if="$route.query.company_id === '5'"></h2>

        <article class="info">
          <p>车牌号：<span>{{ info.plate_num || '未上牌' }}</span></p>
          <p>车主姓名：{{ info.name }}</p>
          <p>订单时间：{{ info.createtime }}</p>
        </article>
      </div>
      <div>
        订单金额：
        <span class="price">{{ info.price }}元</span>
        <span>({{ info.discount }}折)</span>
      </div>
    </header>

    <router-link
      tag="section"
      :to="'/pay-insurance-ratio/' + order_id"
      class="check pl-1 pr-1 mb-1">
      <span>查看交通违法系数</span>
      <span>></span>
    </router-link>

    <section class="check pl-1 pr-1 mb-1" @click="enterDiscount">
      <span>期望折扣</span>
      <span>{{ discount ? discount + '%' : '' }}&nbsp;&nbsp;&nbsp;></span>
    </section>

    <insurance-type-header
      title="商业险"
      color="blue"
      v-if="insurances.basic.length || insurances.others.length"></insurance-type-header>

    <grey-header title="基本险" v-if="insurances.basic.length"></grey-header>

    <ul v-if="insurances.basic.length">
      <li v-for="(item, index) in insurances.basic">
        <span>{{ item.name | short }}</span>
        <span>{{ item.deductible === 1 ? '免' : '' }}</span>
        <span>{{ item.amt | formatThousandFixedTwo }}</span>
        <span>&yen;&nbsp;{{ item.price }}</span>
      </li>
    </ul>

    <grey-header title="附加险" v-if="insurances.others.length"></grey-header>

    <ul v-if="insurances.others.length">
      <li v-for="(item, index) in insurances.others">
        <span>{{ item.name | short }}</span>
        <span>{{ item.deductible === 1 ? '免' : '' }}</span>
        <span>{{ item.name === '玻璃险' ? (+(item.amt) === 1 ? '国产' : '进口') : item.amt | formatThousandFixedTwo }}</span>
        <span>&yen;&nbsp;{{ item.price }}</span>
      </li>
    </ul>

    <insurance-type-header
      v-if="insurances.compulsory.length"
      class="compulsory"
      title="交强险"
      color="red"></insurance-type-header>

    <ul v-if="insurances.compulsory.length">
      <li v-for="(item, index) in insurances.compulsory">
        <span>{{ item.name | short }}</span>
        <span>{{ item.deductible === 1 ? '免' : '' }}</span>
        <span>{{ item.amt | formatThousandFixedTwo }}</span>
        <span>&yen;&nbsp;{{ item.price }}</span>
      </li>
    </ul>

    <div class="public-footer-btn-box">
      <router-link
        tag="button"
        :to="'/pay-insurance-info-confirm/' + $route.params.type + '/' + company_id + '/' + order_id + '?model_id=' + $route.query.model_id + '&in_id=' + $route.params.in_id"
        class="single-button"
        :disabled="submitDisabled">确定
      </router-link>
    </div>

    <popup
      class="codePopup"
      v-model="codePopupShow"
      pop-transition="popup-fade">
      <h3 :class="company"></h3>

      <p>请输入图中验证码</p>
      <p>不区分大小写</p>

      <section v-if="company && this.jqCode">
        <div class="code-box">
          <span>交强险</span>
          <img :src="'data:img/jpg;base64,' + this.jqCode" alt="">
        </div>

        <input
          type="text"
          v-model="jqCodeText"
          v-validate="'required|alpha_num|max:4|min:4'"
          name="验证码">
        <span v-show="VeeErrors.has('验证码')">{{ VeeErrors.first('验证码') }}</span>
      </section>

      <section v-if="company && this.syCode">
        <div class="code-box">
          <span>商业险</span>
          <img :src="'data:img/jpg;base64,' + this.syCode" alt="">
        </div>

        <input
          type="text"
          v-model="syCodeText"
          v-validate="'required|alpha_num|max:4|min:4'"
          name="验证码">
        <span v-show="VeeErrors.has('验证码')">{{ VeeErrors.first('验证码') }}</span>
      </section>

      <div class="public-btn-box">
        <button class="submit" @click="getPriceWithCode(company)">提交</button>
        <button class="back" @click="codePopupShow = false">取消</button>
      </div>
    </popup>
  </div>
</template>

<script>
  import InsuranceTypeHeader from './insurance-type-header.vue';
  import GreyHeader from './grey-header.vue';
  import {MessageBox, Indicator, Toast, popup} from 'mint-ui';

  export default {
    name: "pay-insurance-detail-confirm",
    components: {
      InsuranceTypeHeader,
      GreyHeader,
      MessageBox,
      Indicator,
      popup
    },
    data() {
      return {
        info: {},
        insurances: {
          basic: [],
          others: [],
          compulsory: []
        },
        company_id: '',
        order_id: '',
        submitDisabled: true,
        discount: '',
        jqCode: '',
        jqCodeText: '',
        syCode: '',
        syCodeText: '',
        params: this.$tool.qs.parse(sessionStorage.getItem('INSURANCE_PRICE_BY_CAR')),
        company: '',
        codePopupShow: false
      }
    },
    methods: {
      enterDiscount() {
        MessageBox.prompt('请输入期望折扣(单位%)', '提示', {
          inputType: 'number',
          inputPattern: /^([1-9][0-9]{0,1}){1}(\.[0-9]{1,2})?$/,
          inputErrorMessage: '折扣数大于1小于100，至多含有两位小数'
        }).then(({value, action}) => {
          if (action === 'confirm' && value) {

            this.submitDisabled = true;

            this.getNewParams_update(this.company, '', '', value);

            Indicator.open({
              text: '请稍后',
              spinnerType: 'snake'
            });

            this.$http.post({
              api: this.$api.INSURANCE_PRICE_BY_CAR,
              params: this.params,
              success: (res) => {

                // 非转保车
                if (!res.data.data[this.company].jq_check_code && !res.data.data[this.company].sy_check_code) {

                  sessionStorage.setItem('offer', this.$tool.qs.stringify(res.data));

                  this.getInfo_view();

                  Indicator.close();
                  Toast('已重新获取报价');
                  this.submitDisabled = false;

                  // 转保车
                } else if (res.data.data[this.company].jq_check_code || res.data.data[this.company].sy_check_code) {

                  this.jqCode = res.data.data[this.company].jq_check_code;
                  this.syCode = res.data.data[this.company].sy_check_code;

                  this.codePopupShow = true;
                  this.jqCodeText = '';
                  this.syCodeText = '';

                }
              }
            });
          }
        })
      },

      getNewParams_update(company, jq, sy, discount) {

        if (this.params[company].length === 5) {

          this.params[company].push(sy, jq, discount);

        } else if (this.params[company].length === 8) {

          this.params[company][5] = sy;
          this.params[company][6] = jq;
          this.params[company][7] = discount;
        }

        sessionStorage.setItem('INSURANCE_PRICE_BY_CAR', this.$tool.qs.stringify(this.params));
      },

      getInfo_view() {
        this.$http.post({
          api: this.$api.INSURANCE_DETAIL_CHECK,
          params: {
            model_id: this.$route.query.model_id,
            in_id: this.$route.params.in_id,
            user_id: localStorage.getItem('id'),
            company_id: this.$route.query.company_id
          },
          success: (res) => {
            this.info = res.data.data;
            this.company_id = res.data.data.company_id;
            this.order_id = res.data.data.order_id;

            this.submitDisabled = false;

            let insurances = this.info.crve;

            this.insurances.basic = [];
            this.insurances.others = [];
            this.insurances.compulsory = [];

            for (let i = 0; i < insurances.length; i++) {
              if (insurances[i].type === '1' && insurances[i].insured_type === '1') {
                this.insurances.basic.push(insurances[i]);
              } else if (insurances[i].type === '1' && insurances[i].insured_type === '2') {
                this.insurances.others.push(insurances[i]);
              } else if (insurances[i].type === '2') {
                this.insurances.compulsory.push(insurances[i]);
              }
            }
          }
        });

        this.discount = this.params[this.company][7] || '';
      },

      getPriceWithCode(company) {
        this.$validator.validateAll().then((result) => {
          if (result) {
            this.codePopupShow = false;

            // 只改变该公司的数字参数
            let _params = JSON.parse(JSON.stringify(this.params));
            _params[company][5] = this.syCodeText;
            _params[company][6] = this.jqCodeText;

            this.$http.post({
              api: this.$api.INSURANCE_PRICE_BY_CAR,
              params: _params,
              success: (res) => {

                if (res.data.data[this.company].error_msg === '验证码错误') {

                  this.jqCode = '';
                  this.syCode = '';
                  alert('验证码错误！');

                } else if (!res.data.data[this.company].error_msg) {

                  // 能获取报价 防止刷新更新sessionStorage

                  sessionStorage.setItem('offer', this.$tool.qs.stringify(res.data));

                  this.getInfo_view();
                  Toast('已重新获取报价');

                } else {

                  // 验证码通过，但此公司没有报价

                  alert(res.data.data[this.company].error_msg);

                  // 更新UI 防止刷新更新sessionStorage）

                  sessionStorage.setItem('offer', this.$tool.qs.stringify(res.data));

                  Toast('此公司没有报价');

                  this.$router.back(-1);
                }

                Indicator.close();
                this.submitDisabled = false;
              }
            });
          }
        });
      }
    },
    created() {

      switch (this.$route.query.company_id) {
        case '1':
          this.company = 'ha';
          break;
        case '2':
          this.company = 'astp';
          break;
        case '3':
          this.company = 'dh';
          break;
        case '4':
          this.company = 'rb';
          break;
        case '5':
          this.company = 'bbw';
          break;
        default:
          return;
      }

      this.getInfo_view();
    }
  }
</script>

<style scoped lang="scss">

  #pay-insurance-detail-confirm {
    padding-bottom: $public-footer-btn-box-height;

    > .banner {
      height: 14rem;
      margin-bottom: 1rem;
      background: $white;
      box-shadow: $public-box-shadow;
      border-radius: $public-banner-border-radius;

      > div:first-of-type {
        display: flex;
        align-items: center;
        height: 10rem;
        padding: 0 2.4rem;

        > .logo {
          width: 70px;
          height: 54px;
          background: url("../../assets/images/public/companies-2.png") no-repeat center / $size-as-parent auto;

          &.ha {
            background-position-y: top;
          }

          &.astp {
            background-position-y: -97px;
          }

          &.dh {
            background-position-y: -204px;
          }

          &.rb {
            background-position-y: -301px;
          }

          &.bbw {
            background-position-y: -379px;
          }
        }

        > .info {
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          flex: 1;
          height: $size-as-parent;
          padding-left: 2.6rem;
          font-size: 1.5rem;
          color: #333;

          span {
            font-weight: bold;
            color: #0196ff;
          }
        }
      }

      > div:last-of-type {
        height: 4rem;
        font-size: 1.8rem;
        color: #333;
        line-height: 4rem;
        text-align: center;
        background: #e9f6ff;

        > .price {
          color: #f00;
        }
      }
    }

    > .check {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 4rem;
      background: $white;

      > span:first-of-type {
        font-size: 1.5rem;
      }

      > span:last-of-type {
        font-size: 2rem;
      }
    }

    > .compulsory {
      margin-top: 1rem;
    }

    > ul {
      background: $white;

      > li {

        $li-height: 5rem;

        display: flex;
        width: $size-as-parent;
        height: $li-height;
        padding: 0 1.8rem;
        line-height: $li-height;
        font-size: 1.5rem;
        color: #333;
        border-bottom: 1px solid #eee;

        &:last-of-type {
          border: none;
        }

        > span {
          display: inline-block;

          &:nth-of-type(1) {
            width: 40%;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }

          &:nth-of-type(2) {
            width: 8%;
            color: #999;
          }

          &:nth-of-type(3) {
            width: 26%;
          }

          &:nth-of-type(4) {
            width: 26%;
            overflow-x: scroll;
            overflow-y: hidden;
            white-space: nowrap;
          }
        }
      }
    }

    // todo 公共样式

    > .codePopup {
      text-align: center;
      padding: 2.4rem;

      > p {
        font-size: 1.5rem;
        padding: .6rem;

        &:first-of-type {
          color: #333;
          margin-top: .8rem;
        }

        &:last-of-type {
          color: #999;
        }
      }

      > section {

        $row-height: 4rem;

        position: relative;
        margin-bottom: 1.8rem;

        > .code-box {
          display: flex;
          width: 18rem;
          height: $row-height;
          border: 1px solid #bbb;
          margin-bottom: 1.6rem;

          > span {
            height: $size-as-parent;
            width: 6.8rem;
            font-size: 1.5rem;
            color: #333;
            line-height: $row-height;
            text-align: center;
          }

          > img {
            flex: 1;
            height: $size-as-parent;
          }
        }

        > input {
          width: $size-as-parent;
          height: $row-height;
          padding: .6rem;
          border: 1px solid #bbb;
          border-radius: .6rem;
        }

        > span {
          position: absolute;
          top: $size-as-parent;
          right: 0;
          color: #e4393c;
        }
      }

      > .public-btn-box {
        padding: 0;
        justify-content: space-between;
      }
    }

    h3 {
      display: inline-block;
      width: 108px;
      height: 36px;

      &.ha {
        background: url("../../assets/images/public/companies.png") no-repeat (center 6px) / $size-as-parent auto;
      }

      &.astp {
        background: url("../../assets/images/public/companies.png") no-repeat (center -57px) / $size-as-parent auto;
      }

      &.dh {
        background: url("../../assets/images/public/companies.png") no-repeat (center -118px) / $size-as-parent auto;
      }
    }
  }
</style>
